<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Copy;
use App\Models\Area;
use App\Models\Order;
use App\Models\DoctorWorks;
use App\Util\Url;
use Encore\Admin\Actions\RowAction;
use Encore\Admin\Auth\Database\Administrator;
use Encore\Admin\Controllers\AdminController;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use App\Admin\Extensions\OrderExporter;
use App\Admin\Extensions\ExcelExpoter;
use App\Exports\UsersExport;
use Encore\Admin\Grid\Displayers\Actions;
/**
 * 此项目由百凯伦公司研发，后面省略一万字
 */
class OrderController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '商品订单管理';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Order());
        $grid->disableExport();//禁止导出
        $grid->filter(function ($filter) {
            // 去掉默认的id过滤器
            $filter->disableIdFilter();
            // 在这里添加字段过滤器
            //电话	姓名	商品名称	状态	订单编号	开始时间-截止时间
            $filter->equal('orderaddress.phone', __('电话'));
            $filter->like('orderaddress.name', __('姓名'));
            $filter->like('order_goods.goods_name', __('商品名称'));
            $filter->equal('receive_status', "收货状态")->select([0 => '未收货', 1 => "已收货"]);
            $filter->equal('evaluate_status', "评价状态")->select([0 => '未评价', 1 => "已评价"]);
            $filter->equal('order_status', "订单状态")->select([0 => '未完成', 1 => "已完成", 2 => "申请售后", 3 => "售后完成", 4 => "取消订单"]);
            $filter->equal('sn', __('订单编号'));
            $filter->between('created_at', '订单时间')->datetime();

        });
        $grid->model()->where('order_type', 2)->orderByDesc('id');//只读取商品订单
        $userid = auth()->user()->id ?? 0;
        $roleId = Administrator::find($userid)->roles()->first()->pivot->role_id; //获取角色id
        if ($roleId != 1) {
            $grid->model()->whereRaw('suppliers_id =' . $userid);
        }

        $grid->disableCreateButton();//禁用创建按钮
//        $grid->setActionClass(Grid\Displayers\DropdownActions::class);
        $grid->tools(function (Actions $actions) {
            // 添加操作按钮
            $actions->add(new Copy());
        });
        //设置弹窗宽度
//        \Encore\Admin\Facades\Admin::script('$(".grid-modal .modal-dialog").css("width", "70%");');
        $grid->model()->orderBy('id', 'desc');
        $grid->fixColumns(0, 1);//固定列可滑动列表
        $grid->column('id', __('Id'));
        $grid->column('order_goods', __('商品名称'))->display(function () {
            return $this->order_goods->goods_name ?? '';
        });

        $grid->column('order_goods_pic', __('商品图片'))->display(function () {
            if (!empty($this->order_goods->goods_img)) {
                return Url::getHttpHost() . 'upload/' . $this->order_goods->goods_img;
            }
        })->lightbox(['width' => 50, 'height' => 50]);
        $grid->column('sn', __('订单编号'));
        $grid->column('order_source', __('商品类型'))->display(function () {
            switch ($this->order_source) {
                case 1:
                    return '工作室';
                case 2:
                    return '供应商';
                default:
                    return '无';
            }
        });
        $grid->column('distributor.name', __('所属供应商'));
        $grid->column('work.work_name', __('所属医护工作室'));

        $grid->column('product_standard', __('商品规格'))->display(function () {
            return $this->order_goods->product_standard ?? '';
        });
        $grid->column('product_remark', __('商品备注'))->display(function () {
            return $this->order_goods->product_remark ?? '';
        });
        $grid->column('orderaddress.name', __('收货人姓名'));
        $grid->column('orderaddress.phone', __('联系方式'));
        $grid->column('order_delivery_addr', __('详细地址'))->display(function () {
            $area = new Area();
            $province_name = $area->where('code', $this->orderaddress->province_id ?? 0)->value('name');
            $city_name = $area->where('code', $this->orderaddress->city_id ?? 0)->value('name');
            $district_name = $area->where('code', $this->orderaddress->district_id ?? 0)->value('name');
            $detail = $this->orderaddress->detail ?? '';
            return $province_name . '->' . $city_name . '->' . $district_name . '->' . $detail;
        });
        $grid->column('nums', __('商品数量'));
        $grid->column('created_at', __('创建时间'));
        $grid->column('pay_time', __('支付时间'));
        $radio = [
            0 => '未完成',
            1 => '已完成',
            2 => '申请售后',
            3 => '售后完成',
            4 => '取消订单',
        ];
        $grid->column('order_status', __('订单状态'))->radio($radio);
        $grid->column('total_price', __('订单总价格'));
        /*
        $grid->column('sn', __('订单号'))->modal("订单商品", function ($model) {
            $list = $model->ordergoods()->paginate(20, ['*'], 'row' . $this->id)
                ->appends('page', request('page'));
            $pagination = $list->toHtml();
            $array = $list->map(function ($list) {
                return $list->only(['id', 'goods_name', 'goods_num', 'goods_price', 'pay_price', 'goods_img', 'created_at']);
            })->toArray();
            $data = [];
            $width = 200;
            $height = 200;
            foreach ($array as $key => $item) {
                $src = $item['goods_img'];
                $item['goods_img'] = "<img src='$src' style='max-width:{$width}px;max-height:{$height}px' class='img' />";
                $data[$key] = $item;
            }
            $array[]['id'] = $pagination;    //追加分页代码到新行的第一列
            return new Table(['id', '商品名称', '购买数', '商品价格', '支付价格', '商品图片', '下单日期'], $data);

        });
        */

        /*

        $grid->column('user_id', __('用户'))->display(function () {
            return User::find($this->user_id)->name;
        });
        $grid->column('order_price', __('订单价格'));
        $grid->column('pay_price', __('支付价格'));
        $grid->column('total_price', __('订单总价格'));
        $grid->column('logis_price', __('物流费用'))->hide(); //隐藏
        $grid->column('pay_type', __('支付方式'))->display(function () {
            switch ($this->pay_type) {
                case 1:
                    return '微信';
                case 2:
                    return '支付宝';
                case 3:
                    return '余额';
                case 4:
                    return '代付';
                default:
                    return '无支付方式';
            }
        });
        $grid->column('order_type', __('商品类型'))->display(function () {
            switch ($this->order_type) {
                case 1:
                    return '课程';
                case 2:
                    return '商品';
                case 3:
                    return '打赏';
                case 4:
                    return '图文质询';
                case 5:
                    return '电话质询';
                default:
                    return '无';
            }
        });

        $grid->column('pay_status', __('是否支付'))->display(function () {
            switch ($this->pay_status) {
                case 0:
                    return '未支付';
                case 1:
                    return '已支付';
                default:
                    return '无';
            }
        });

        $grid->column('delivery_status', __('发货状态'))->display(function () {
            switch ($this->delivery_status) {
                case 0:
                    return '未发货';
                case 1:
                    return '已发货';
                default:
                    return '无';
            }
        });
        $grid->column('delivery_time', __('发货时间'));
        $grid->column('receive_status', __('收货状态'))->display(function () {
            switch ($this->receive_status) {
                case 0:
                    return '已收货';
                case 1:
                    return '已发货';
                default:
                    return '无';
            }
        });
        $grid->column('receive_time', __('收货时间'));
        $grid->column('remarks', __('备注'));
        $grid->column('evaluate_status', __('评价状态'))->display(function () {
            switch ($this->evaluate_status) {
                case 0:
                    return '未评价';
                case 1:
                    return '已评价';
                default:
                    return '无';
            }
        });
        */
        /**
         * 创建模态框
         */
        /*$this->script = <<<EOT
        $('.grid-row-pass').unbind('click').click(function() {
            var id = $(this).data('id');
            swal({
                title: "确认同意该用户的退款申请吗？",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {
                    $.ajax({
                        method: 'get',
                        url: '/admin/refund/' + id,
                        success: function (data) {
                            console.log(data);
                            $.pjax.reload('#pjax-container');
                            if(data.code){
                                swal(data.msg, '', 'success');
                            }else{
                                swal(data.msg, '', 'error');
                            }
                        }
                    });
                }
            });
        });

        $('.grid-row-refuse').unbind('click').click(function() {
            var id = $(this).data('id');
            swal({
                title: "确认拒绝该用户的退款申请吗？",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {
                    $.ajax({
                        method: 'get',
                        url: '/admin/refuse/' + id,
                        success: function (data) {
                            console.log(data);
                            $.pjax.reload('#pjax-container');
                            if(data.code){
                                swal(data.msg, '', 'success');
                            }else{
                                swal(data.msg, '', 'error');
                            }
                        }
                    });
                }
            });
        });
EOT;
        Admin::script($this->script);*/

        $grid->exporter(new OrderExporter());
//        $grid->exporter(new ExcelExpoter());
        return $grid;
    }

    public function sale($id)
    {
        dd($id);
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Order::findOrFail($id));
        $show->panel()->tools(function ($tools) {
            $tools->disableDelete();
            $tools->disableEdit();
        });
        $show->field('id', __('Id'));
        $show->field('sn', __('订单号'));
        //订单状态(0:未完成,1:已完成2:申请售后3:售后完成4:取消订单)
        $show->field('order_status', __('订单状态'))->as(function () {
            switch ($this->order_status) {
                case 0:
                    return '未完成';
                case 1:
                    return '已完成';
                case 2:
                    return '申请售后';
                case 3:
                    return '售后完成';
                case 4:
                    return '取消订单';
                default:
                    return '无';
            }
        });
        $show->field('created_at', __('创建时间'));
        $show->field('remarks', __('订单备注'));
        $show->field('pay_time', __('支付时间'));
        $show->field('orderaddress.name', __('收货人姓名'));
        $show->field('orderaddress.phone', __('联系方式'));
        $show->field('order_delivery_addr', __('收货地址'))->as(function () {
            $area = new Area();
            $province_name = $area->where('code', $this->orderaddress->province_id ?? 0)->value('name');
            $city_name = $area->where('code', $this->orderaddress->city_id ?? 0)->value('name');
            $district_name = $area->where('code', $this->orderaddress->district_id ?? 0)->value('name');
            $detail = $this->orderaddress->detail ?? '';
            return $province_name . '->' . $city_name . '->' . $district_name . '->' . $detail;
        });
        $show->field('order_source', __('商品类型'))->as(function () {
            switch ($this->order_source) {
                case 1:
                    return '工作室';
                case 2:
                    return '供应商';
                default:
                    return '无';
            }
        });

        $show->field('order_goods', __('商品名称'))->as(function () {
            return $this->order_goods->goods_name ?? '';
        });

        $show->field('order_goods_pic', __('商品图片'))->as(function () {
            if (!empty($this->order_goods->goods_img)) {
                return Url::getHttpHost() . 'upload/' . $this->order_goods->goods_img;
            }
        })->image(['width' => 50, 'height' => 50]);
        $show->field('product_standard', __('商品规格'));
        $show->field('nums', __('商品数量'));
        $show->field('suppliers_id', __('所属供应商'))->as(function () {
            $res = Administrator::find($this->suppliers_id);
            return $res->name ?? '';
        });
        $show->field('work_id', __('所属医护工作室'))->as(function () {
            return (new DoctorWorks())->getName($this->work_id);
        });

        /*
        $show->field('work', __('工作室LOG'))->as(function () {
            return $this->work->logo;
        })->image(Url::getHttpHost() . 'upload/', 100, 100);
        $show->field('work.work_name', __('工作室名称'));
        $show->field('work.call', __('工作室电话'));

        $show->field('nums', __('商品数'));
        $show->field('order_price', __('订单价格'));
        $show->field('pay_price', __('支付价格'));
        $show->field('total_price', __('订单总价格'));
        $show->field('logis_price', __('物流费用'));
        $show->field('pay_type', __('支付方式'))->as(function () {
            switch ($this->pay_type) {
                case 1:
                    return '微信';
                case 2:
                    return '支付宝';
                case 3:
                    return '余额';
                case 4:
                    return '代付';
                default:
                    return '无';
            }
        });
        $show->field('order_type', __('商品类型'))->as(function () {
            switch ($this->order_type) {
                case 1:
                    return '课程';
                case 2:
                    return '商品';
                case 3:
                    return '打赏';
                case 4:
                    return '图文质询';
                case 5:
                    return '电话质询';
                default:
                    return '无';
            }
        });

        $show->field('pay_status', __('是否支付'))->as(function () {
            switch ($this->pay_status) {
                case 1:
                    return '已支付';
                case 0:
                    return '未支付';
                default:
                    return '无';
            }
        });

        $show->field('delivery_status', __('发货状态'))->as(function () {
            switch ($this->delivery_status) {
                case 1:
                    return '已发货';
                case 0:
                    return '未发货';
                default:
                    return '无';
            }
        });
        $show->field('delivery_time', __('发货时间'));
        $show->field('receive_status', __('收货状态'))->as(function () {
            switch ($this->receive_status) {
                case 1:
                    return '已收货';
                case 0:
                    return '未收货';
                default:
                    return '无';
            }
        });
        $show->field('receive_time', __('收货时间'));
        $show->field('remarks', __('备注'));
        $show->field('evaluate_status', __('评价状态'))->as(function () {
            switch ($this->evaluate_status) {
                case 1:
                    return '已评价';
                case 0:
                    return '未评价';
                default:
                    return '无';
            }
        });
        $show->field('evaluate_time', __('评价时间'));

        $show->field('updated_at', __('修改时间'));
        */
        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        //收货人姓名
        //联系方式
        //收货地址
        //订单状态
        //商品数量
        $form = new Form(new Order());
        $form->tools(function (Form\Tools $tools) {
            // 去掉`删除`按钮
            $tools->disableDelete();
        });

        $form->text('sn', __('订单号'));
        $form->text('orderaddress.name', __('收货人姓名'));
        $form->mobile('orderaddress.phone', __('联系方式'));
        $form->distpicker(['orderaddress.province_id', 'orderaddress.city_id', 'orderaddress.district_id'], '请选择区域');
        $form->text('orderaddress.detail', __('收货地址'));
        //订单状态(0:未完成,1:已完成2:申请售后3:售后完成4:取消订单)
        $option = [
            0 => '未完成',
            1 => '已完成',
            2 => '申请售后',
            3 => '售后完成',
            4 => '取消订单',
        ];
        $form->radio('order_status', __('订单状态'))->options($option)->default("");
        $form->number('nums', __('订单数'))->default(1);
        $form->textarea('remarks', __('订单备注'));
//        $form->decimal('order_price', __('Order price'));
//        $form->decimal('pay_price', __('Pay price'));
//        $form->decimal('total_price', __('Total price'));
//        $form->decimal('logis_price', __('Logis price'));
//        $form->switch('pay_type', __('Pay type'));
//        $form->switch('order_type', __('Order type'));
//        $form->datetime('pay_time', __('Pay time'))->default(date('Y-m-d H:i:s'));
//        $form->switch('pay_status', __('Pay status'));
//        $form->switch('order_status', __('Order status'));
//        $form->switch('delivery_status', __('Delivery status'));
//        $form->datetime('delivery_time', __('Delivery time'))->default(date('Y-m-d H:i:s'));
//        $form->switch('receive_status', __('Receive status'));
//        $form->datetime('receive_time', __('Receive time'))->default(date('Y-m-d H:i:s'));
//        $form->number('evaluate_status', __('Evaluate status'));
//        $form->datetime('evaluate_time', __('Evaluate time'))->default(date('Y-m-d H:i:s'));

        return $form;
    }
}
